#!/usr/bin/python
from nodi import *
import sys,os,pickle

def usage():
	print "Lista comandi"
	print "--------------------------------------------------------------------"
	print "Lista dei nodi e delle macchine in uso: ./onevm.py list"
	print "Lanciare una macchina virtuale X su un nodo Y: ./onevm.py deploy X Y PASSWORD"
	print "Rimuovere dal nodo Y la macchina con listening X: ./onevm.py remove X Y"
def freevnc(nodo):
	for i in range(2,99):
		if os.path.exists("dump/"+nodo+"/"+str(i)) == False:
			return i
	return -1
	
def main ():
	if os.path.exists("dump") == False:
		os.mkdir("dump")
	if len(sys.argv) == 1:
		usage()
		sys.exit(0)
	if sys.argv[1] == "list":
		if len(sys.argv) != 2:
			usage()
			sys.exit(0)	
		print "LISTA NODI"
		print "ID"+"\t"+"NOME_NODO"
		for i in range(0,len(nodi)):
			print str(i) + "\t" + nodi[i]
		print "\n\nMACCHINE VIRTUALI DISPONIBILI"
		print "ID"+"\t"+"NOME"
		for i in range(0,len(machine)):
			print str(i) + "\t" + machine[i]
		print "\n\nLISTA MACCHINE VIRTUALI ATTIVE"
		listing = os.listdir("dump")
		for infile in listing:
			read_node = os.listdir("dump/"+infile)
			print "NODO - "+nodi[int(infile)]
			print "--------------------------"
			for info in read_node:
				fd_info = open("dump/"+infile+"/"+info)
				print fd_info.read()
				fd_info.close()
				
		sys.exit(0)
	if sys.argv[1] == "deploy":
		if len(sys.argv) != 5 or sys.argv[2].isdigit() != True or sys.argv[3].isdigit() != True or int(sys.argv[2]) >= len(machine) or int(sys.argv[3]) >= len(nodi) or len(sys.argv[4]) < 6:
			usage()
			sys.exit(0)
		if os.path.exists("dump/"+sys.argv[3]) == False:
			os.mkdir("dump/"+sys.argv[3])
		newvnc = str(freevnc(sys.argv[3]))
		if os.path.exists("dump/"+sys.argv[3]+"/"+newvnc) == False:
			fd = open("dump/"+sys.argv[3]+"/"+newvnc,"wt")
			fd.write(machine[int(sys.argv[2])]+"\n"+"port: "+str(5900+int(newvnc))+"\n")
			fd.close()
		os.system('ssh '+ nodi[int(sys.argv[3])] +' "nohup echo change vnc password '+sys.argv[4]+' |  qemu-system-i386 -cdrom '+machine[int(sys.argv[2])]+' -net user -net nic,model=ne2k_pci -m 100 -vnc :'+newvnc+',password -redir udp:'+str(30000+int(newvnc))+'::55555 -monitor stdio &"&')
		print "vncviewer "+nodi[int(sys.argv[3])]+":"+newvnc
	if sys.argv[1] == "remove":
		if len(sys.argv) != 4 or sys.argv[2].isdigit() != True or sys.argv[2].isdigit() != True or int(sys.argv[3]) >= len(nodi):
			usage()
			sys.exit(0)
		os.system('ssh '+ nodi[int(sys.argv[3])] +' "./killbyvnc.sh '+sys.argv[2]+'"')
		os.remove("dump/"+sys.argv[3]+"/"+sys.argv[2])
if __name__ == "__main__":
    sys.exit(main())
